package com.soyuan.util;

import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * Created by twx on 2017/8/22.
 */
public class HttpClientUtil {
    private static final Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);

    public static OkHttpClient client;

    public static OkHttpClient getClient() {
        if (client==null)
            client =  new OkHttpClient.Builder().readTimeout(5000, TimeUnit.MILLISECONDS).build();
        return client;
    }

    public static String doPost(String url,String postStr) {
        String res=null;

        Request request = new Request.Builder()
                .url(url)  // http://localhost:8888/
                .post(RequestBody.create(MediaType.parse("application/json"),postStr))
                .build();
        Response response=null;
        try {
            response = getClient().newCall(request).execute();
            res =  response.body().string();
            if (!response.isSuccessful()) {
                logger.error("ETL返回的错误信息: "+res);
                logger.error(" 错误代码 "+response.code());
                logger.error("MongoClient 发送到ETL的数据是 "+postStr);
                res = null;
                //throw new IOException("服务器端错误: " + res);
            }
            //logger.debug("响应代码："+response.code());
        } catch (IOException e) {
            logger.error("连接ETL失败: "+e.getMessage()+" 此次连接URL的"+url);
            logger.error("此次MongoClient 发送到ETL的数据是 "+postStr);
        }finally {
            if (response != null) {
                response.close();
            }
        }
        return res;
    }

    public static boolean testConn(String url) {
        boolean status = false;
        Request request = new Request.Builder().url(url).build();
        Response response=null;
        try {
            response = getClient().newCall(request).execute();
            response.close();
            if (!response.isSuccessful()) {
                logger.error("连接ETL响应不成功，响应代码"+response.code()+" 此次连接URL的"+url);
            }else{
                status = true;
                logger.info("连接ETL成功");
            }
        } catch (Exception e) {
            logger.error("连接ETL失败: "+e.getMessage()+" 此次连接URL的"+url);
            e.printStackTrace();
        }finally {
            if (response!=null)
                response.close();
        }
        return status;
    }

    public static void main(String[] args) {
        boolean status = testConn("http://localhost:8080/");
        System.out.println("llll"+status);
    }
}
